package com.lovo.shiro;


import com.lovo.bean.UserBean;
import com.lovo.result.GlobalHandleException;
import com.lovo.service.IUserService;
import com.lovo.utill.WebUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class JWTRealm extends AuthorizingRealm {
    @Resource
    private IUserService userInfoService;
//    @Resource
//    private IGradeService functionInfoService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录的用户
        UserBean userInfoBean = (UserBean) principalCollection.getPrimaryPrincipal();
        //通过SimpleAuthenticationInfo做授权
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        List<RoleBean> roleInfoBeans = userInfoBean.getRoleList();
//        List<GradeBean> functionInfoBeans = userInfoBean.getGradeList();
//        for (RoleBean role : roleInfoBeans) {
//            //添加角色
//            simpleAuthorizationInfo.addRole(role.getRoleName());
//        }
//        for (GradeBean function : functionInfoBeans) {
//            //添加权限
//            simpleAuthorizationInfo.addStringPermission(function.getGradeName());
//        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getPrincipal();
        if(token == null){
            return new SimpleAuthenticationInfo(null,"",getName());
        }
        UserBean userInfoBean = null;
        try {
            userInfoBean = WebUtil.verifyToken(token,userInfoService);
        } catch (GlobalHandleException e) {}
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userInfoBean,token,getName());
        return simpleAuthenticationInfo;
    }
}
